package com.tuyan.aixiang.api.helper;

import android.net.ParseException;

import com.google.gson.JsonParseException;
import com.tuyan.aixiang.MainApplication;
import com.tuyan.aixiang.R;
import com.tuyan.aixiang.util.Log;


import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import retrofit2.HttpException;


/**
 * 本地异常处理。包括解析异常等其他异常
 */

public class CustomException {
    private static final String TAG = "CustomException";

    /**
     * 未知错误
     */
    public static final int UNKNOWN = 1000;

    /**
     * 解析错误
     */
    public static final int PARSE_ERROR = 1001;

    /**
     * 网络错误
     */
    public static final int NETWORK_ERROR = 1002;


    /**
     * 协议错误
     */
    public static final int HTTP_ERROR = 1003;

    public static ApiException handleException(Throwable e) {
        Log.e(TAG, e);
        ApiException ex;
        if (e instanceof JsonParseException
                || e instanceof JSONException
                || e instanceof ParseException) {
            //解析错误
            ex = new ApiException(PARSE_ERROR, e.getMessage(), MainApplication.getAppContext().getResources().getString(R.string.parse_error));
            return ex;
        } else if (e instanceof ConnectException) {
            //网络错误
            ex = new ApiException(NETWORK_ERROR, e.getMessage(), MainApplication.getAppContext().getResources().getString(R.string.network_error));
            return ex;
        } else if (e instanceof UnknownHostException || e instanceof SocketTimeoutException) {
            //连接错误
            ex = new ApiException(NETWORK_ERROR, e.getMessage(), MainApplication.getAppContext().getResources().getString(R.string.network_error));
            return ex;
        }
//        else if (e instanceof HttpException){
//            Integer code = ((HttpException) e).code();
//            ex = new ApiException()
//        }
        else {
            //未知错误
            ex = new ApiException(UNKNOWN, e.getMessage(), MainApplication.getAppContext().getResources().getString(R.string.unknow_error));
            return ex;
        }
    }
}
